<?php
require_once(Mage::getBaseDir('lib')."/K3/k3.class.php");
class Silk_Zgb_Adminhtml_WarehouseController extends Mage_Adminhtml_Controller_Action
{
	protected function _initAction()
	{
			$this->loadLayout()->_setActiveMenu("zgb/warehouse")->_addBreadcrumb(Mage::helper("adminhtml")->__("配送员管理"),Mage::helper("adminhtml")->__("配送员管理"));
			return $this;
	}
	public function indexAction() 
	{
		    $this->_title($this->__("轻松老板"));
		    $this->_title($this->__("配送员管理"));

			$this->_initAction();
			$this->renderLayout();
	}
	public function editAction()
	{			    
		    $this->_title($this->__("轻松老板"));
			$this->_title($this->__("配送员"));
		    $this->_title($this->__("修改"));
			
			$id = $this->getRequest()->getParam("id");
			$model = Mage::getModel("zgb/warehouse")->load($id);
			if ($model->getId()) {
				Mage::register("warehouse_data", $model);
				$this->loadLayout();
				$this->_setActiveMenu("zgb/warehouse");
				$this->_addBreadcrumb(Mage::helper("adminhtml")->__("配送员管理"), Mage::helper("adminhtml")->__("配送员管理"));
				$this->_addBreadcrumb(Mage::helper("adminhtml")->__("配送员信息"), Mage::helper("adminhtml")->__("配送员信息"));
				$this->getLayout()->getBlock("head")->setCanLoadExtJs(true);
				$this->_addContent($this->getLayout()->createBlock("zgb/adminhtml_warehouse_edit"))->_addLeft($this->getLayout()->createBlock("zgb/adminhtml_warehouse_edit_tabs"));
				$this->renderLayout();
			} 
			else {
				//Mage::getSingleton("adminhtml/session")->addError(Mage::helper("zgb")->__("配送员不存在."));
				$this->_redirect("*/*/");
			}
	}

	public function newAction()
	{

	$this->_title($this->__("轻松老板"));
	$this->_title($this->__("配送员"));
	$this->_title($this->__("新建"));

    $id   = $this->getRequest()->getParam("id");
	$model  = Mage::getModel("zgb/warehouse")->load($id);

	$data = Mage::getSingleton("adminhtml/session")->getFormData(true);
	if (!empty($data)) {
		$model->setData($data);
	}

	Mage::register("warehouse_data", $model);

	$this->loadLayout();
	$this->_setActiveMenu("zgb/warehouse");

	$this->getLayout()->getBlock("head")->setCanLoadExtJs(true);

	$this->_addBreadcrumb(Mage::helper("adminhtml")->__("配送员管理"), Mage::helper("adminhtml")->__("配送员管理"));
	$this->_addBreadcrumb(Mage::helper("adminhtml")->__("配送员信息"), Mage::helper("adminhtml")->__("配送员信息"));


	$this->_addContent($this->getLayout()->createBlock("zgb/adminhtml_warehouse_edit"))->_addLeft($this->getLayout()->createBlock("zgb/adminhtml_warehouse_edit_tabs"));

	$this->renderLayout();

	}
	public function saveAction()
	{

		$post_data=$this->getRequest()->getPost();
		//获取站点
		$websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
		if ($post_data) {
			try {
				if(!$this->getRequest()->getParam("id"))
				{
					$admin = Mage::getModel("admin/user");
				}else{
					$model= Mage::getModel("zgb/warehouse")->load($this->getRequest()->getParam("id"));
					$adminId = $model->getAdminId();
					$admin = Mage::getModel("admin/user")->load($adminId);
				}
				$admin->setFirstname($this->getRequest()->getParam("name"));
				$admin->setLastname($this->getRequest()->getParam("contact_name"));
				$admin->setEmail(rand(0, 999999) . date('Ymd') . '@hahahui.com');
				$admin->setUsername($this->getRequest()->getParam("login_name"));
				$admin->setPassword($this->getRequest()->getParam('password'));
				$admin->setPhone($this->getRequest()->getParam('contact_phone'));
				$admin->setIsActive($this->getRequest()->getParam('status'));
				$admin->setWebsiteId($websiteId);
				if ($admin->userExists()) {
					throw new Exception("配送员名已存在");
				}
				$admin->save();
				$admin->setRoleIds(array(Mage::helper('zgb')->getRoleId('warehouse')))
					->setRoleUserId($admin->getUserId())
					->saveRelations();
				$role = Mage::getModel('api2/acl_global_role')->load(3);
				if ($role && $role->getId()) {
					$resourceModel = Mage::getResourceModel('api2/acl_global_role');
					$resourceModel->saveAdminToRoleRelation($admin->getUserId(), 3);
				}

				$model = Mage::getModel("zgb/warehouse")
				->addData($post_data)
				->setId($this->getRequest()->getParam("id"));

				if(!$this->getRequest()->getParam("id"))
				{
					$model->setAdminId($admin->getId());
				}

				$model->save();

				Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("配送员添加成功！"));
				Mage::getSingleton("adminhtml/session")->setWarehouseData(false);

				if ($this->getRequest()->getParam("back")) {
					$this->_redirect("*/*/edit", array("id" => $model->getId()));
					return;
				}
				$this->_redirect("*/*/");
				return;
			} 
			catch (Exception $e) {
				Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
				Mage::getSingleton("adminhtml/session")->setWarehouseData($this->getRequest()->getPost());
				$this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
			return;
			}

		}
		$this->_redirect("*/*/");
	}



	public function deleteAction()
	{
			if( $this->getRequest()->getParam("id") > 0 ) {
				try {
					$model = Mage::getModel("zgb/warehouse");
					$model->setId($this->getRequest()->getParam("id"))->delete();
					Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("已删除！"));
					$this->_redirect("*/*/");
				} 
				catch (Exception $e) {
					Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
					$this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
				}
			}
			$this->_redirect("*/*/");
	}

	
	public function massRemoveAction()
	{
		try {
			$ids = $this->getRequest()->getPost('ids', array());
			foreach ($ids as $id) {
                  $model = Mage::getModel("zgb/warehouse")->load($id);
				  $admin = Mage::getModel("admin/user");
				  $admin->setId($model->getAdminId())->delete();
				  $model->delete();
			}
			Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("已删除！"));
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}

		public function massChangeStatusAction()
		{
			$status = $this->getRequest()->getPost('status');
			try {
				$ids = $this->getRequest()->getPost('ids', array());
				foreach ($ids as $id) {
					$model = Mage::getModel("zgb/warehouse")->load($id);
					$model->setStatus($status);
					$model->save();
					$admin = Mage::getModel("admin/user");
					if($model->getAdminId()){
						$admin->load($model->getAdminId())->setIsActive($status)->save();
					}
				}
				Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("状态已改变！"));
			}
			catch (Exception $e) {
				Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
			}
			$this->_redirect('*/*/');
		}
		
	/**
	 * Export order grid to CSV format
	 */
	public function exportCsvAction()
	{
		$fileName   = 'warehouse.csv';
		$grid       = $this->getLayout()->createBlock('zgb/adminhtml_warehouse_grid');
		$this->_prepareDownloadResponse($fileName, $grid->getCsvFile());
	} 
	/**
	 *  Export order grid to Excel XML format
	 */
	public function exportExcelAction()
	{
		$fileName   = 'warehouse.xml';
		$grid       = $this->getLayout()->createBlock('zgb/adminhtml_warehouse_grid');
		$this->_prepareDownloadResponse($fileName, $grid->getExcelFile($fileName));
	}

	protected function _isAllowed()
    {
    	return true;
        return Mage::getSingleton('admin/session')->isAllowed('zgb');
    }

    public function inventoryUpdateAction()
    {
    	$data = array('error'=>true,'message'=>'');
    	$storeId = $this->getRequest()->getParam('store');
    
    	$productId = $this->getRequest()->getParam('product_id');	
    	$websiteId = $this->_getWebsiteId();
    	if(!$storeId){
    		$storeId = Mage::getModel("core/website")->load($websiteId)->getDefaultStore()->getId();
    	}
    	if(!$storeId)
    	{
    		$data['message'] = "请先选择地区";
    		echo Zend_Json::encode($data);
    		return;
    	}
    	$qty = intval($this->getRequest()->getParam('qty'));
    	if($qty<=0)
    	{
    		$data['message'] = "请输入数量!";
    		echo Zend_Json::encode($data);
    		return;
    	}

    	$operation = $this->getRequest()->getParam('operation');
    	if($operation == 2)
    	{   
    		//判断出库数量是否大于库存
    		$resource = Mage::getSingleton('core/resource');
    		$db = $resource->getConnection('core_read');
    		$sql = "select * from aitoc_cataloginventory_stock_item where product_id='{$productId}' and website_id='{$websiteId}'";
    		$query = $db->fetchAll($sql);
    		foreach ($query as $value) {
    			$result = $value["qty"];
    		}
    		if($qty>$result){
    		    $data["message"] = "出库数量大于库存";
    		    echo Zend_Json::encode($data);
    		    return;
    		}
    		
    		if($qty>0) $qty = -$qty;
    	}
    	if($qty<0)
    	{
    		$operation = 2;
    	}
    	$session = Mage::getSingleton('admin/session');
    	$adminId = $session->getUser()->getId();
    	$comment = $this->getRequest()->getParam('comment');
    	$date = date("Y-m-d H:i:s");
    	$resource = Mage::getSingleton('core/resource');
    	$db = $resource->getConnection('core_read');
    	$db->beginTransaction();
    	$sql = "insert into aitoc_inventory_stock(website_id,product_id,qty,operation,created_at,admin_id,comment)
    	values('{$websiteId}','{$productId}','{$qty}','{$operation}','{$date}','{$adminId}','{$comment}')";
    	$db->exec($sql);
    	try
    	{
    	$product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($productId);
    	$stockItem = Mage::getModel('cataloginventory/stock_item')->setStoreId($storeId)->loadByProduct($product);
    	$originQty = $stockItem->getQty();
    	if(!$originQty){
    	$stockItemq = Mage::getModel('cataloginventory/stock_item');
    	$stockItemq->setProductId($productId);
    						$stockItemq->setWebsiteId($websiteId);
    	    						$stockItemq->setStockId(1);
    	    						$stockItemq->setQty(0);
    	    						$stockItemq->save();
    	    						$originQty =$stockItemq->getQty();
    	}
    	}catch(Exception $e){
    	$db->rollback();
    	$data["message"] = $e->getMessage();
    	echo Zend_Json::encode($data);
    	return;
    	}
    	$totalQty = $qty + $originQty;
    	if ($totalQty > 0) {
    	$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=1 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    	} else {
    	$sql = "update aitoc_cataloginventory_stock_item set qty='{$totalQty}',is_in_stock=0 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
    	}
    	$db->exec($sql);
    	$db->commit();
    	if($product && $product->getId())
    	{
    	$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
    	$stockItem->setQty($totalQty);
    	$stockItem->save();
    	}
    	$data["message"] = "库存保存成功";
    	echo Zend_Json::encode($data);
    }

    public function inventoryGridAction()
    {
    	$this->loadLayout()->renderLayout();
    }

    protected function _getWebsiteId(){
        $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
        return $websiteId;
    }
   	public function qtyUpdateAction()
	{
		$productId = $this->getRequest()->getParam('product_id');
		$storeId = $this->getRequest()->getParam('store');
		$product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($productId);
		if($product && $product->getId())
		{
			echo intval($product->getStockItem()->getQty());
		}
	}

}
